
import sql_deal 
import requests
import random
import jwt
import datetime
import json
import os
# import cv2

sign_key ="lyb_test_2023"

#授权校验
def check_auth(token):

    status =False
    msg =None
    # token = auth_header[7:]
    phone =None
    old_time = None
    try:
        payload = jwt.decode(token, sign_key, algorithms=['HS256'])
        status =True
        phone = payload.get('phone')
        old_time = payload.get('now_time')
        # nick_name = payload.get('nick_name')
        msg="成功"
    except jwt.InvalidTokenError:
        msg='Invalid token'
        status = False
        return msg,status,phone

    now_time = datetime.datetime.now().strptime("%Y-%m-%d")
    if old_time!=None:
        if now_time !=old_time.split(" ")[0]:
            msg='时间已过期'
            status = False
            return msg,status,phone
        
    # msg = "成功"
    return msg,status,phone


def login_user(user_name,password):
    sql_data={}
    table ="management"
    sql_data["user_name"] = user_name
    sql_data["password"] = password
    select_result = sql_deal.select_data_list(sql_data,table)
    return select_result

#手机号校验
def phone_check(phone,in_time=None):
    sql_data={}
    table ="person"
    sql_data["phone"] = phone
    select_result = sql_deal.select_data_list(sql_data,table)
    member =0

    status =False
    #搜索数据库
    if select_result!=None and select_result!=() and select_result!=[] and len(select_result)>0:
        one_result = select_result[0]
        nick_name = one_result["nick_name"]
        member = one_result["member"]
        status =True
    else:
        #姓名拼接
        n =""
        for i in range(7):
            m = random.randint(0,9)
            n = n+str(m)
        nick_name = "学员"+ n

        #插入到数据库
        sql_data={}
        table ="person"
        sql_data["phone"] = phone
        sql_data["nick_name"] = nick_name
        if in_time!=None:
            sql_data["time"] = in_time
        insert_result = sql_deal.insert_data_list(sql_data,table)
        print()


    return nick_name,status,member


#更新个人信息的接口
def update_person_info(update_info,phone):
    status =False
    if update_info!=None and update_info!={}:
        table="person"
        # update_sql ={}
        search_sql ={}
        search_sql["phone"] = phone
        update_result = sql_deal.update_target_list(table,update_info,search_sql=None)
        if update_result!=None and update_result!=0:
            status =True
    
    return update_result,status


#更新个人信息的接口
def person_info(phone):
    status =False
    table="person"

    sql_data ={}
    sql_data["phone"] = phone
    select_result = sql_deal.select_data_list(sql_data,table)
    if select_result!=None and select_result!=[] and select_result!=() and len(select_result)>0:
        status =True

    return select_result,status



#更新个人信息的接口
def card_info(phone):
    status =False
    table="person_card"

    sql_data ={}
    sql_data["phone"] = phone
    select_result = sql_deal.select_data_list(sql_data,table)
    if select_result!=None and select_result!=[] and select_result!=() and len(select_result)>0:
        status =True

    return select_result,status

#更新个人信息的接口
def update_person_card(update_info,phone):
    status =False
    if update_info!=None and update_info!={}:
        table="person_card"
        # update_sql ={}
        search_sql ={}
        search_sql["phone"] = phone
        update_result = sql_deal.update_target_list(table,update_info,search_sql=None)
        if update_result!=None and update_result!=0:
            status =True
    
    return update_result,status



def get_my_buy(phone):
    sql_data={}
    table ="my_buy"
    sql_data["phone"] = phone
    select_result = sql_deal.select_data_list(sql_data,table)

    status =False

    course_list =[]

    #搜索数据库
    if select_result!=None and select_result!=() and select_result!=[] and len(select_result)>0:
        for one_result in select_result:
            course_id = one_result["course_id"]

            #课程
            sql_data={}
            table ="course"
            sql_data["id"] = course_id
            select_result = sql_deal.select_data_list(sql_data,table)

            if select_result!=None and select_result!=() and select_result!=[] and len(select_result)>0:
                for one_result in select_result:
                    course_list.append(one_result)

    return course_list,status

#获取课程
def update_course(search_sql,update_sql):
    table = "course"
    select_result = sql_deal.update_target_list(table,update_sql,search_sql=search_sql)

    return select_result


#获取课程
def get_course(word=None,page_id=1,page_number=10):
    if page_id>0:
        page_id =page_id-1
    table = "course"
    if word ==None or word =="":
        sql = "select * from {table}  order by id limit {page_id}, {page_number};".format(table=table,page_id=page_id*page_number,page_number=page_number)
    else:
        sql = "select * from {table}  where title like '%{word}%' or  author like '%{word}%'  order by id limit {page_id}, {page_number};".format(table=table,word=word,page_id=page_id*page_number,page_number=page_number)

    select_result = sql_deal.select_with_sql(sql)

    return select_result

#获取课程
def get_course_total(word=None):
    count_number =0
    
    table = "course"
    if word ==None or word =="":
        sql = "select count(id) as count from {table};".format(table=table)
    else:
        sql = "select count(id) as count from {table}  where title like '%{word}%' or  author like '%{word}%' ;".format(table=table,word=word)
    select_result = sql_deal.select_with_sql(sql)
    
    if select_result!=() and select_result!=[] and select_result!=None:
        count_number = select_result[0]["count"]
    return count_number


#获取课程
def get_person(word=None,page_id=0,page_number=10):
    table = "person"
    if word ==None or word =="":
        sql = "select * from {table}  order by id limit {page_id}, {page_number};".format(table=table,page_id=page_id*page_number,page_number=page_number)
    else:
        sql = "select * from {table}  where nick_name like '%{word}%' or  phone like '%{word}%'  order by id limit {page_id}, {page_number};".format(table=table,word=word,page_id=page_id*page_number,page_number=page_number)

    select_result = sql_deal.select_with_sql(sql)

    return select_result

#获取课程
def update_person(search_sql,update_sql):
    table = "person"
    select_result = sql_deal.update_target_list(table,update_sql,search_sql=search_sql)

    return select_result

#获取课程
def get_product_list(word=None,page_id=0,page_number=10):
    table = "woniuhui_product"
    if word ==None or word =="":
        sql = "select title,head_image,id from {table}  order by id limit {page_id}, {page_number};".format(table=table,page_id=page_id*page_number,page_number=page_number)
    else:
        sql = "select title,head_image,id from {table}  where title like '%{word}%' or type like '%{word}%'  order by id limit {page_id}, {page_number};".format(table=table,word=word,page_id=page_id*page_number,page_number=page_number)

    select_result = sql_deal.select_with_sql(sql)

    return select_result


#章节搜索
def get_chapter(course_id,word=None,page_id=0,page_number=10):
    table = "chapter"
    if word ==None or word =="":
        sql = "select * from {table} where course_id={course_id} order by id limit {page_id}, {page_number};".format(table=table,course_id= course_id,page_id=page_id*page_number,page_number=page_number)
    else:
        sql = "select * from {table}  where course_id={course_id} and title like '%{word}%'   order by id limit {page_id}, {page_number};".format(table=table,course_id=course_id,word=word,page_id=page_id*page_number,page_number=page_number)

    select_result = sql_deal.select_with_sql(sql)
    for x in range(len(select_result)):
        if "date" in select_result[x].keys():
            select_result[x]["date"]  = datetime.datetime.strftime(select_result[x]["date"], "%Y-%m-%d")
    return select_result

def get_hot():
    table = "course"
    sql_data={}
    sql_data["hot"] =1
    select_result = sql_deal.select_data_list(sql_data,table)
    for x in range(len(select_result)):
        if "date" in select_result[x].keys():
            select_result[x]["date"]  = datetime.datetime.strftime(select_result[x]["date"], "%Y-%m-%d")
    return select_result


def course_by_id(course_id):
    table = "course"
    sql_data={}
    sql_data["id"] =course_id
    select_result = sql_deal.select_data_list(sql_data,table)
    return select_result

def info_product_table(product_id,table):
    sql_data={}
    sql_data["id"] =product_id
    select_result = sql_deal.select_data_list(sql_data,table)
    return select_result

#课程退款
def my_refund(course_id,phone):
    status =False
    msg=""

    table ="my_buy"
    sql_data={}
    sql_data["course_id"] = course_id
    sql_data["phone"] = phone

    select_result = sql_deal.select_data_list(sql_data,table)
    if select_result =="" or select_result==None or select_result==[] or select_result==():
        msg="无此课程"
    else:
        one_result = select_result[0]

        table ="my_refund"
        sql_data={}
        sql_data["course_id"] = course_id
        sql_data["phone"] = phone
        sql_data["status"] = 0
        sql_data["price"] = one_result["price"]
        sql_data["person_id"] = one_result["person_id"]
        sql_data["time"] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        insert_result = sql_deal.insert_data_list(sql_data,table)
        if insert_result !=None:
            msg = "成功"
            status=True
        else:
            msg ="退款失败"

    return msg,status
            
#获取token
def get_wechat_token():
    token =None
    params = {'grant_type': 'client_credential', 'appid': 'wx01e315a1f1f0d156','secret':'599210b768dd0bcf7ef8c63701003da4'}
    url = "https://api.weixin.qq.com/cgi-bin/token"
    res = requests.get(url = url, params=params)
    get_json = json.loads(res.text)
    now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if type(get_json) == dict:
        get_json["now_time"] = now_time

        #记录到配置文件
        f = open("config.txt","w")
        f.write(json.dumps(get_json))
        f.close
    print(get_json)
    return get_json


#获取手机号
def get_phone(code):

    if os.path.exists("config.txt"):
        f = open("config.txt","r")
        lines = f.read()
        f.close
        get_json = json.loads(lines)
    else:
        get_json = get_wechat_token()
    
    old_time = get_json["now_time"]
    old_time = datetime.datetime.strptime(old_time, "%Y-%m-%d %H:%M:%S")
    now_time = datetime.datetime.now()

    differ_time = (now_time-old_time).seconds
    if differ_time>5400:
        get_json = get_wechat_token()

    ACCESS_TOKEN = get_json["access_token"]
    url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s"%(ACCESS_TOKEN)
    json_data = {}
    json_data["code"] = code
    res = requests.post(url = url,json=json_data)
    run_result = json.loads(res.text)
    print(run_result)
    return run_result

#插入留言
def insert_comment(one_data):
    status = False
    table ="comment"
    insert_result = sql_deal.insert_data_list(one_data,table)
    if insert_result!=None and insert_result!=0 and insert_result!="":
        status = True
    return status

#插入留言
def get_comment(one_data):
    status = False
    table ="comment"
    select_result = sql_deal.select_all(one_data,table)
    
    if select_result!=None and select_result!=0 and select_result!="":
        status = True
    for x in range(len(select_result)):
        if "date" in select_result[x].keys():
            select_result[x]["date"]  = datetime.datetime.strftime(select_result[x]["date"], "%Y-%m-%d")
    return status,select_result

#获取到标签
def get_icon():
    files = os.listdir("image")
    image_list=[]
    nav_icon_list =[]
    m = "http://120.79.96.200:8111/image/"
    for one_image in files:
        if "icon_" in one_image:
            if  "_nav_icons_" in one_image:
                
                nav_icon_list.append(m+one_image)
            else:
                image_list.append(m+one_image)
    nav_icon_list.sort()
    print(image_list,nav_icon_list)
    return image_list,nav_icon_list


#获取到标签
def get_lunbo():
    files = os.listdir("image")
    image_list=[]
    m = "http://120.79.96.200:8111/image/"
    for one_image in files:
        if "lunbo_" in one_image:
            image_list.append(m+one_image)
    image_list.sort()
    return image_list

#
# def gen(camera):
#     while True:
#         success, image = camera.read()
#         if not success:
#             break
#         ret, jpeg = cv2.imencode('.jpg', image)
#         frame = jpeg.tobytes()
#         yield (b'--frame\r\n'
#                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

#


# get_course(word=None,page_id=0,page_number=10)

# get_course(word ="iu",page_id=0)


# phone = "14155873749"
# phone_check(phone)
# for i in range(20):
#     m = random.randint(0,9)
#     print(m)
# phone = "14155767648"
# get_my_buy(phone)
# get_wechat_token()

# ACCESS_TOKEN="70_fnpfhuq8hxibeE0UCaNJVZ182nr3WuEfOT28lz46VKw_YN90lOjT8yO87055OUaqaVGe6SjbeKDCqKsH9plPMm92slTFPWT0l7wJMsYm8au6b00tqJLqxW9TKyoMZYcAAAWJI"
code = "c1ccea04fc62358823320c8430b10eff6d0a30b30f5335c88a00df69c39a178b"
code ="d7b2dee822fb8235f8b66f6eed4636e9c1338a24c09dbd645ba8e5df1de99015"
# get_phone(code)

# get_icon()
# gen(camera)











